<template>
  <div class="user-information">
    <div class="title">
      个人信息
    </div>
    <div class="content">
      <div class="account">
        <div class="account—title">
          账户信息
          <span style="color:#999999;font-weight: normal;
          margin-left: 400px;cursor: pointer" @click="logoutAndPush">退出登录</span>
        </div>
        <div class="phone-information">
          手机号：<span class="phone" v-text="">{{ user.mobile | changeMobile }}</span>
        </div>
        <div class="modify">
          <span class="el-icon-edit"></span>
          <span class="change-password" @click="changePassword">
            修改密码
          </span>
        </div>
      </div>
      <div class="personal-data">
        <div class="personal-title">
          个人资料
        </div>
        <div class="personal-form" style="text-align: left">
          <el-form ref="form"
                   :label-position="'top'"
                   :rules="rules"
                   :model="user">
            <el-form-item label="用户头像：" prop="face" style="height: 150px;">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="'http://localhost:30000/oss/fileOss'">
                <div class="block"><el-avatar :size="100" :src="user.face"></el-avatar></div>
              </el-upload>

            </el-form-item>
            <el-form-item label="用户名：" prop="nickName" style="height: 70px;">
              <el-input v-model="user.nickName" style="width: 305px;"/>
            </el-form-item>
            <!--头像-->
            <!--            <el-form-item>
                          <el-upload
                          class="avatar-uploader"
                          :show-file-list="true"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload"
                          :action="'http://localhost:30000/oss/fileOss'">
                          <img v-if="imageUrl" :src="user.face" class="avatar">
                          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
          </el-form-item>-->
            <el-form-item label="性别：" prop="gender" style="height: 70px;">
              <el-radio v-model="user.gender" :label="1">男</el-radio>
              <el-radio v-model="user.gender" :label="0">女</el-radio>
            </el-form-item>
            <el-form-item label="生日" prop="birthday" style="height: 70px;">
              <el-col :span="11">
                <el-form-item prop="date1">
                  <el-date-picker type="date" placeholder="选择日期" v-model="user.birthday" style="width: 100%;"/>
                </el-form-item>
              </el-col>
              <el-col style="color: rgb(192, 196, 204);">
                未满14周岁的未成年人尚不能成为我们的用户，请通过父母或者监护人的账户来下单或参与我们的活动。
              </el-col>
            </el-form-item>
            <el-form-item label="手机：" prop="mobile">
              <el-input v-model="user.mobile" style="width: 305px;"/>
            </el-form-item>
            <el-form-item label="邮箱：" style="height: 70px;" prop="email">
              <el-input v-model="user.email" style="width: 305px;"/>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="agree"
                           @change="changeAgree"></el-checkbox>
              <!--              <el-radio v-model="agree"-->
              <!--                        @change="clearAgree"-->
              <!--                        label="1"></el-radio>-->
              <span>我接受章程，并承诺我已经阅读修改条约</span>
            </el-form-item>
            <el-form-item style="height: 70px;">
              <el-button style="background-color: white;color: #333333" @click="clearData">重置</el-button>
              <el-button style="background-color: #122147;color: #FFFFFF" @click="onUpdate" :disabled="disabled">修改
              </el-button>
            </el-form-item>
          </el-form>

        </div>
      </div>
    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="centerDialogVisible"
      :close-on-click-modal="false"
      @closed="closedDialog()"
      width="30%"
      center>
      <el-form :rules="passwordRules" :label-position="'top'" label-width="80px" :model="updatePassword">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="updatePassword.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="updatePassword.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="updatePassword.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submit">提交</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUser, logout, userUpdate, submitChangePassword } from '@/api'

export default {
  name: 'UserInformation',
  data () {
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.updatePassword.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      user: {
        uid: '',
        nickName: '',
        face: '',
        gender: '1',
        birthday: '',
        mobile: '',
        email: ''
      },
      agree: 0,
      disabled: true,
      rules: {
        nickName: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }, {
          min: 2,
          max: 5,
          message: '长度在 3 到 16 个字符'
        }
          //{ pattern:/^[a-zA-Z]w{1,4}$/, message: '以字母开头，长度在2-5之间， 只能包含字符、数字和下划线'}
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value) == false) {
                callback(new Error('请输入正确的邮箱'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      passwordRules: {
        oldPassword: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        newPassword: [{
          required: true,
          message: '请输入新密码',
          trigger: 'blur'
        }],
        confirmPassword: [{
          required: true,
          message: '请确认新密码',
          trigger: 'blur'
        }, {
          validator: validatePass2,
          trigger: 'blur',
          required: true
        }]
      },
      centerDialogVisible: false, // 修改密码弹框是否显示
      updatePassword: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  filters: {
    // 过滤手机号码为中间四个*
    changeMobile (mobile) {
      if (mobile !== undefined && mobile !== null && mobile !== '') {
        return mobile.substring(0, 3) + '****' + mobile.substring(7, 11)
      }
    }
  },
  created () {
    this.initUserData()
  },
  methods: {
    initUserData () {
      // 在页面加载时读取sessionStorage
      if (sessionStorage.getItem('store')) {
        // sessionStorage中存在用户信息就放到store里
        this.$store.replaceState(Object.assign({},
          this.$store.state,
          JSON.parse(sessionStorage.getItem('store'))))
      }
      // 在页面刷新时将store保存到sessionStorage里
      window.addEventListener('beforeunload', () => {
        sessionStorage.setItem('store', JSON.stringify(this.$store.state))
      })
      this.user = this.$store.state.user
      if (JSON.stringify(this.user) === '{}') {
        getUser().then(({ data }) => {
          if (data.code === 0) {
            this.$store.state.user = data.data
            sessionStorage.setItem('store', JSON.stringify(this.$store.state))
          }
        }).catch((res) => {
          console.log(res)
        })
      }
    },
    clearData () {
      this.user = {}
    },
    changeAgree (label) {
      this.disabled = !label
    },
    logoutAndPush () {
      this.$confirm('您确定退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        logout().then(({ data }) => {
          if (data.code === 0) {
            this.$store.state.user = {}
            sessionStorage.removeItem('store')
            this.$message({
              type: 'success',
              message: '退出成功!'
            })
            // this.$router.push({ path: '/index' })
            this.$router.replace('/index')
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出操作'
        })
      })

    },

     handleAvatarSuccess(res, file) {
       console.log(res);
       this.user.face = res.url
     },
     beforeAvatarUpload(file) {
       const isJPG = file.type === 'image/jpeg';
       const isLt2M = file.size / 1024 / 1024 < 2;

       if (!isJPG) {
         this.$message.error('上传头像图片只能是 JPG 格式!');
       }
       if (!isLt2M) {
         this.$message.error('上传头像图片大小不能超过 2MB!');
       }
       return isJPG && isLt2M;
     },

    // 修改个人信息
    onUpdate () {
      let user = {}
      user.uid = this.user.uid
      user.nickName = this.user.nickName
      user.gender = this.user.gender
      user.birthday = this.user.birthday
      user.mobile = this.user.mobile
      user.email = this.user.email
      user.face = this.user.face
      userUpdate(user)
        .then(({ data }) => {
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: '修改成功！'
            })
            // 清除掉用户数据，重新获取
            this.$store.state.user = {}
            sessionStorage.removeItem('store')
            // 跳转到首页
            this.$router.push({ path: '/index' })
            getUser().then(({ data }) => {
              if (data.code === 0) {
                this.$store.state.user = data.data
                sessionStorage.setItem('store', JSON.stringify(this.$store.state))
              }
            }).catch((res) => {
              console.log(res)
            })
          } else {
            this.$message.error(data.msg)
          }
        })
    },
    changePassword () {
      this.centerDialogVisible = true
    },
    submit () {
      if (this.updatePassword.oldPassword === ''
        || this.updatePassword.newPassword === ''
        || this.updatePassword.confirmPassword === ''){
        return
      }
      // 提交修改密码的请求
      submitChangePassword(this.user.uid,
        this.updatePassword.oldPassword,
        this.updatePassword.newPassword).then(({ data }) => {
        if (data.code === 0){
          this.centerDialogVisible = false
          this.$message.success("密码修改成功！")
        }else {
          this.$message.error(data.msg)
        }
      }).catch(res => {
        console.log(res)
      })

    },
    closedDialog () {
      this.updatePassword = {}
    }
  }
}
</script>

<style scoped lang="less">
.user-information {
  background-color: #f4f4f4;

  .title {
    height: 34px;
    width: 100%;
    font-weight: 400;
    font-size: 18px;
    text-align: left;
  }

  .content {
    border-radius: 5px;

    .account {
      height: 130px;
      width: 100%;
      padding: 24px 18px;
      text-align: left;
      background-color: white;
      box-sizing: border-box;

      .account—title {
        color: #333;
        font-weight: 700;
        font-size: 16px;
        line-height: 16px;
      }

      .phone-information {
        color: #999;
        margin-top: 24px;

        .phone {
          color: #333333;
        }
      }

      .modify {
        margin-top: 10px;
        font-size: 14px;

        .change-password {
          cursor: pointer;
        }
      }
    }

    .personal-data {
      margin-top: 20px;
      background-color: white;
      padding: 16px 24px;

      .personal-title {
        text-align: left;
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
}
</style>
